package com.shop.utils;

import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.template.Engine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * creat_user:  denghuanqing
 * creat_date: 2018/1/5
 * creat_time: 19:03
 * describe: 完成替换模板写文件
 **/
public class RenderCode {
    /**
     * 根据具体模板生成代码
     *
     * @param templateFileName 模板文件名称  放在resource目录codeTemplate文件夹下
     * @param kv               map类型数据
     * @param filePath         输出文件路径
     * @return
     */
    public static boolean render(String templateFileName, Kv kv, StringBuilder filePath) {
        BufferedWriter output = null;
        try {
            String baseTemplatePath = PathKit.getWebRootPath() + "/src/main/resources/codeTemplate";

            File file = new File(filePath.toString());

            File path = new File(file.getParent());
            if (!path.exists()) {
                path.mkdirs();
            }
            output = new BufferedWriter(new FileWriter(file));

            Engine.use()
                    .setBaseTemplatePath(baseTemplatePath)
                    //.setSourceFactory(new ClassPathSourceFactory())
                    .getTemplate(templateFileName)
                    .render(kv, output);

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (output != null) output.close();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {
        render("model.html", Kv.by("data", "2222"), new StringBuilder(PathKit.getWebRootPath() + "/src/main/java/com/shop/controller/UserController.java"));
    }
}
